package com.hank.demo1.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hank.demo1.service.ApiService;
import org.springframework.stereotype.Service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApiServiceImpl implements ApiService {

    /**
     * 下面两个填AK和SK，也就是日日新网站上的东西👇👇👇
     */
    static String access_key_id = "2Uv9rGnRm2V8iJKtkwPG2T9jhvx";
    static String secret_access_key = "zsnFd97iEW2TubWldUbcwUElLQBjx4Z5";

    @Override
    public String getTableJson(String str) throws Exception {

        URL url = new URL("https://api.sensenova.cn/v1/llm/chat-completions");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        //获取Token👇👇👇👇
        String auth = contextLoads();

        // 设置请求头👇👇👇
        conn.setRequestProperty("Authorization", "Bearer "+auth);
        conn.setRequestProperty("Content-Type", "application/json");

        // 设置请求体👇👇👇
        ObjectMapper objectMapper = new ObjectMapper();

        //微调这里👇👇👇这里是拼接问句的地方
        String data = "{\"messages\": [{\"content\": \"下面是我的需求："+str+"，通过上述文字给我返回一个表结构，表名和字段名请加上中文名称, 以JSON结构返回,请只返回JSON结果，不要其他任何内容，返回JSON示例为 {“tables”: [{“tableName”:“t1”, “tableTitle”:“表1”,“columns”:[{“columnName”:“c1”, “columnTitle”:“字段1”, “relationship”: {“table”:“t2”}}]}]}]}\",\"role\": \"user\"}],\"model\": \"nova-ptc-xs-v1\"}";

        //这里是发送请求👇👇👇
        try(OutputStream os = conn.getOutputStream()) {
            byte[] input = data.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        //获取请求码👇👇👇
        int responseCode = conn.getResponseCode();

        //判断请求吗，是200说明调用成功👇👇👇
        if (responseCode == HttpURLConnection.HTTP_OK) { //success
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }

            //关闭请求连接👇👇👇
            in.close();
            conn.disconnect();

            //处理返回得到的结果👇👇👇
            JsonNode rootNode = objectMapper.readTree(content.toString());
            JsonNode dataNode = rootNode.get("data");
            JsonNode choicesNode = dataNode.get("choices");
            JsonNode messageNode = choicesNode.get(0).get("message");
            System.out.println(messageNode);

            //返回处理好的结果👇👇👇
            return messageNode.toString();
        } else {
            //请求码不是200的话，说明请求失败👇👇👇
            System.out.println("POST request not worked");
        }

        //关闭连接👇👇👇
        conn.disconnect();
        return null;
    }

    /**
     * 获取Token的方法👇👇👇，不用动
     * @return
     */
    String contextLoads() {
        try {
            Date expiredAt = new Date(System.currentTimeMillis() + 18000*1000);
            Date notBefore = new Date(System.currentTimeMillis() - 5*10000);
            Algorithm algo = Algorithm.HMAC256(secret_access_key);
            Map<String, Object> header = new HashMap<>();
            header.put("alg", "HS256");
            return JWT.create()
                    .withIssuer(access_key_id)
                    .withHeader(header)
                    .withExpiresAt(expiredAt)
                    .withNotBefore(notBefore)
                    .sign(algo).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
